import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/ShopPage/OtherUserListPage.dart';
import 'package:BeeApp/ShopPage/UserAddLocationPage.dart';
import 'package:BeeApp/ShopPage/UserLocationModelPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;

class UserMainPage02 extends StatefulWidget {
  UserMainPage02({Key key}) : super(key: key);

  @override
  _UserMainPage02State createState() => _UserMainPage02State();
}

class _UserMainPage02State extends State<UserMainPage02> {
  final otherPriceText = TextEditingController();
  final beiZhuText = TextEditingController();

  LocationModel sendLocationModel;
  LocationModel reciveLocationModel;
  String sendID = "";
  String reciveID = "";
  String allPriceStr = "0.00";
  String bannerStr = "";
  String timeStr = "现在发货";

  List<String> daysArr = [];
  List<String> showDaysArr = [];
  List showTime = [
    "上午 6:00-12:00",
    "下午 12:00-18:00",
    "晚上 0:00-6:00",
    "凌晨 0:00-6:00",
    "1:00",
    "2:00",
    "3:00",
    "4:00",
    "5:00",
    "6:00",
    "7:00",
    "8:00",
    "9:00",
    "10:00",
    "11:00",
    "12:00",
    "13:00",
    "14:00",
    "15:00",
    "16:00",
    "17:00",
    "18:00",
    "19:00",
    "20:00",
    "21:00",
    "22:00",
    "23:00",
    "24:00"
  ];

  @override
  void initState() {
    super.initState();
    updays();
    if (mounted) {
      uploadBanner();
      upLoadAddress();
    }
  }

  void updays() {
    var today = DateTime.now(); // 2019-11-08 02:54:53.218443

    for (var i = 1; i < 8; i++) {
      var fiftyDaysFromNow = today.add(new Duration(days: i));
      String daysStr = fiftyDaysFromNow.month.toString() +
          "-" +
          fiftyDaysFromNow.day.toString();
      daysArr.add(daysStr);
      if (i == 1) {
        showDaysArr.add("今天");
      } else if (i == 2) {
        showDaysArr.add("明天");
      } else {
        showDaysArr.add(fiftyDaysFromNow.month.toString() +
            "月" +
            fiftyDaysFromNow.day.toString() +
            "日");
      }
    }
  }

  void uploadBanner() {
    DioUtils.postHttp(
      context,
      "index/banner",
      parameters: {"type": "2"},
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              bannerStr = t["data"]["logo_image"].toString();
            });
          }
        }
      },
    );
  }

  //货主默认收发货地址
  void upLoadAddress() {
    DioUtils.postHttp(
      context,
      "goodsuser/default_address",
      parameters: {"token": getData("token")},
      onSuccess: (t) {
        print(t);
        if (mounted) {
          MainModel model = MainModel.fromJson(t);
          if (model.code == 1 && model.data != null) {
            setState(() {
              if (!ObjectUtil.isEmpty(t["data"]["send"]) &&
                  sendLocationModel == null) {
                sendLocationModel = LocationModel.fromJson(t["data"]["send"]);
                sendID = sendLocationModel.id.toString();
                print("发货地址ID$sendID");
              }
              if (!ObjectUtil.isEmpty(t["data"]["recive"]) &&
                  reciveLocationModel == null) {
                print("object000000");
                reciveLocationModel =
                    LocationModel.fromJson(t["data"]["recive"]);
                reciveID = reciveLocationModel.id.toString();
                print("收货地址ID$reciveID");
              }
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          upAllPrice();
        },
        child: Column(
          children: [
            Expanded(
              child: ListView(
                children: <Widget>[
                  bannerStr.length > 0 ? bannerView() : Container(),
                  SizedBox(height: setHeight(10)),
                  address(sendLocationModel, true),
                  lineView(),
                  address(reciveLocationModel, false),
                  SizedBox(height: setHeight(10)),
                  Container(height: 8, width: 8000, color: Colors.grey[400]),
                  newsView(),
                ],
              ),
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.only(
                left: setWidth(30),
                top: 10,
                right: setWidth(30),
                bottom: 10,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  allPrice(),
                  btnView(),
                ],
              ),
            ),
            SizedBox(height: bottomBarHeight),
          ],
        ),
      ),
    );
  }

  Widget bannerView() {
    return Container(
      height: setHeight(170),
      child: CachedNetworkImage(
        imageUrl: bannerStr,
        fit: BoxFit.cover,
      ),
    );
  }

  Widget address(LocationModel locationModel, bool isSend) {
    return Container(
      color: Colors.white,
      child: Row(
        children: <Widget>[
          leftView(isSend),
          Expanded(
            child: locationModel == null
                ? topBtnView(isSend)
                : InkWell(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => UserAddLocationPage(isSend)),
                      ).then((value) {
                        if (value != null) {
                          LocationModel model = value;
                          print("object${model.address}");
                          if (mounted) {
                            setState(() {
                              if (isSend) {
                                sendLocationModel = model;
                                sendID = sendLocationModel.id.toString();
                                print(sendLocationModel.address);
                              } else {
                                reciveLocationModel = model;
                                reciveID = reciveLocationModel.id.toString();
                                print(reciveID);
                              }
                            });
                          }
                        } else {
                          upLoadAddress();
                        }
                        // upLoadAddress();
                      });
                    },
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        addressNewsText(locationModel.title),
                        addressNewsText(locationModel.address +
                            locationModel.buildingNumber),
                        addressNewsText(
                          "${locationModel.realname}  ${locationModel.mobile}",
                        ),
                      ],
                    ),
                  ),
          ),
          locationModel == null ? Container() : chooseAddressView(isSend),
          SizedBox(width: setWidth(40)),
        ],
      ),
    );
  }

  Widget topBtnView(bool isSend) {
    return InkWell(
      child: Container(
        alignment: Alignment.centerLeft,
        height: setHeight(120),
        child: Text(
          isSend ? "请填写发货人信息" : "请填写收货人信息",
          style: TextStyle(
            color: Color(0xFF999999),
            fontSize: setFontSize(28),
          ),
        ),
      ),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => UserAddLocationPage(isSend)),
        ).then((value) {
          print("object$value");
          if (value != null) {
            LocationModel model = value;
            print("object${model.address}");
            if (mounted) {
              setState(() {
                if (isSend) {
                  sendLocationModel = model;
                  sendID = sendLocationModel.id.toString();
                  print(sendLocationModel.address);
                } else {
                  reciveLocationModel = model;
                  reciveID = reciveLocationModel.id.toString();
                  print(reciveID);
                }
              });
            }
          } else {
            upLoadAddress();
          }
        });
      },
    );
  }

  Widget addressNewsText(String string) {
    return Text(
      string,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(28),
      ),
    );
  }

  Widget lineView() {
    return Container(
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            padding: EdgeInsets.fromLTRB(
              setWidth(50),
              setHeight(0),
              setWidth(20),
              setHeight(0),
            ),
            child: Container(
              height: setHeight(56),
              width: setHeight(56),
              alignment: Alignment.center,
              child: Image.asset("images/MainChangeVImage.png"),
            ),
          ),
          Expanded(child: Container(height: 1, color: Colors.grey[300])),
          SizedBox(width: setWidth(60)),
        ],
      ),
    );
  }

  Widget chooseAddressView(bool isSend) {
    return Container(
        alignment: Alignment.center,
        child: InkWell(
          child: Container(
            height: setHeight(48),
            width: setWidth(130),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xFF94DBF0),
              borderRadius: BorderRadius.all(Radius.circular(6)),
              border: Border.all(color: Color(0xFF009CC9), width: 2), //边框
            ),
            child: Text(
              "常用",
              style: TextStyle(
                color: Color(0xFF222222),
                fontSize: setFontSize(22),
              ),
            ),
          ),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => OtherUserListPage(isSend)),
            ).then((value) {
              print("object$value");
              if (value != null) {
                LocationModel model = value;
                if (mounted) {
                  setState(() {
                    if (isSend) {
                      sendLocationModel = model;
                      sendID = sendLocationModel.id.toString();
                      print(sendLocationModel.address);
                    } else {
                      reciveLocationModel = model;
                      reciveID = reciveLocationModel.id.toString();
                      print(reciveID);
                    }
                  });
                }
              } else {
                upLoadAddress();
              }
            });
          },
        ));
  }

  Widget newsView() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
        left: setWidth(30),
        top: 10,
        right: setWidth(30),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "货物信息:",
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: setFontSize(30),
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 10),
          numberView01(),
          otherPrice(),
          // SizedBox(height: 10),
          Row(
            children: [timeView(), Expanded(child: Container())],
          ),
          SizedBox(height: 10),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: <Widget>[
          //     allPrice(),
          //     btnView(),
          //   ],
          // ),
          // SizedBox(height: 20),
        ],
      ),
    );
  }

  Widget numberView01() {
    return Container(
      height: 120,
      padding: EdgeInsets.fromLTRB(10, 8, 10, 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
        border: Border.all(color: Colors.black, width: 1), //边框
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Text(
                "*",
                style: TextStyle(
                    fontSize: setFontSize(30), color: Color(0xFFFF1313)),
              ),
              Text(
                "备注说明:",
                style: TextStyle(
                  fontSize: setFontSize(32),
                  color: Color(0xFF222222),
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(width: 4),
              Expanded(
                child: TextField(
                  minLines: 1,
                  maxLines: 5,
                  controller: beiZhuText,
                  textAlign: TextAlign.start,
                  cursorColor: Colors.grey[400], //设置光标
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入货物详情...",
                    hintStyle: TextStyle(
                      fontSize: setFontSize(32),
                      color: Color(0xFF999999),
                    ),
                  ),
                  style: TextStyle(
                    fontSize: setFontSize(32),
                    color: Color(0xFF999999),
                  ),
                  onChanged: (text) {
                    //内容提交(按回车)的回调
                    print('submit $text');
                    upAllPrice();
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget otherPrice() {
    return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(
                "小费(选填):",
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(28),
                  fontWeight: FontWeight.bold,
                ),
              ),
              Container(
                // height: 30,
                width: 60,
                child: TextField(
                  controller: otherPriceText,
                  textAlign: TextAlign.start,
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  cursorColor: Colors.grey[400], //设置光标
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "0.00",
                      hintStyle: TextStyle(
                          fontSize: setFontSize(28), color: Color(0xFFAEAEAE))),
                  style: TextStyle(
                    fontSize: setFontSize(28),
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.bold,
                  ),
                  onChanged: (text) {
                    //内容提交(按回车)的回调
                    print('submit $text');
                    upAllPrice();
                  },
                ),
              ),
              Text(
                "元",
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(28),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          Text(
            "20kg以下，29寸行李箱以内。",
            style: TextStyle(
              color: Color(0xFFFF3D3D),
              fontSize: setFontSize(22),
            ),
          )
        ]);
  }

  Widget timeView() {
    return Container(
      padding: EdgeInsets.all(4),
      decoration: BoxDecoration(
        border: Border.all(color: Color(0xFF666666), width: 1), //边框
      ),
      child: InkWell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 判断展示文字的长度  和控件的长度
            Text(timeStr),
            Image.asset(
              "images/ShowMoreImage.png",
              height: setWidth(40),
            ),
          ],
        ),
        onTap: () {
          print("object");
          print("object");
          var bb = [showDaysArr, showTime];
          JhPickerTool.showArrayPicker(context, data: bb,
              clickCallBack: (var index, var strData) {
            print(index);
            print(strData);
            print(index.toString());
            print(strData.toList());
            setState(() {
              timeStr = strData.toList()[0] + " " + strData.toList()[1];
            });
          });
        },
      ),
    );
  }

  Widget allPrice() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Text(
          "共计:",
          style: TextStyle(color: Colors.black, fontSize: setFontSize(34)),
        ),
        Text(
          (NumUtil.getNumByValueDouble(double.parse(allPriceStr), 2))
              .toStringAsFixed(2),
          style: TextStyle(fontSize: setFontSize(36), color: Colors.black),
        ),
        Text(
          "元",
          style: TextStyle(color: Colors.black, fontSize: setFontSize(34)),
        ),
      ],
    );
  }

  Widget btnView() {
    return Container(
        alignment: Alignment.center,
        child: InkWell(
          child: mainBtnView("       确认下单       "),
          onTap: () {
            showPayView(context);
          },
        ));
  }

  void upAllPrice() {
    if (otherPriceText.text == "0.00") {
      return;
    }

    Map<String, dynamic> dic = Map();
    dic["token"] = getData("token");
    dic["order_type"] = "2";
    dic["send_address_id"] = sendID;
    dic["recive_address_id"] = reciveID;

    dic["tips"] =
        ObjectUtil.isEmpty(otherPriceText.text) ? "0.00" : otherPriceText.text;

    DioUtils.postHttp(
      context,
      "goodsuser/order_price",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        if (t["code"].toString() == "1") {
          setState(() {
            allPriceStr = t["data"]["order_price"].toString();
          });
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  void showPayView(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      enableDrag: false, //设置不能拖拽关闭
      isDismissible: false, //设置不能点击消失
      isScrollControlled: true,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext context, setBottomSheetState) {
            return InkWell(
              child: Container(
                height: 180,
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(15),
                      topRight: Radius.circular(15)),
                ),
                child: ListView(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("请选择支付方式"),
                        IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    ),
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        InkWell(
                          child: choosePayView(
                              "images/WeiXinPayImage.png", "微信支付"),
                          onTap: () async {
                            var isInstalled = await fluwx.isWeChatInstalled;
                            if (!isInstalled) {
                              showToast("拉取信息失败，请先安装微信");
                              return;
                            }
                            Navigator.of(context).pop();
                            createOrder("2");
                          },
                        ),
                        InkWell(
                          child:
                              choosePayView("images/AliPayImage.png", "支付宝支付"),
                          onTap: () async {
                            var isInstalled = await tobias.isAliPayInstalled();
                            if (!isInstalled) {
                              showToast("未检测到支付宝应用");
                              return;
                            }
                            Navigator.of(context).pop();
                            createOrder("1");
                          },
                        ),
                        InkWell(
                          child: choosePayView(
                              "images/MainOtherPayImage.png", "货到付款"),
                          onTap: () {
                            Navigator.of(context).pop();
                            createOrder("3");
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              onTap: () {
                setBottomSheetState(() {
                  FocusScope.of(context).requestFocus(FocusNode());
                });
              },
            );
          },
        );
      },
    );
  }

  Widget choosePayView(String imageStr, String title) {
    return Column(
      children: [
        Image.asset(
          imageStr,
          height: setHeight(100),
          width: setHeight(100),
        ),
        SizedBox(height: 10),
        Text(
          title,
          style: TextStyle(
            color: Color(0xFF222222),
            fontSize: setFontSize(30),
          ),
        ),
      ],
    );
  }

  void createOrder(String payType) {
    removeFocus(context);
    if (sendID.length == 0) {
      showToast("请选择发货地址");
      return;
    }
    if (reciveID.length == 0) {
      showToast("请选择收货地址");
      return;
    }

    if (beiZhuText.text.length == 0) {
      showToast("请输入货物备注信息");
      return;
    }
    if (double.parse(allPriceStr) == 0) {
      showToast("当前订单价格为0，无法发货");
      return;
    }

    Map<String, dynamic> dic = Map();
    dic["token"] = getData("token");
    dic["order_type"] = "2";
    dic["send_address_id"] = sendID;
    dic["recive_address_id"] = reciveID;
    dic["pay_type"] = payType;
    if (timeStr == "现在发货") {
      List<String> strarr = DateTime.now().toString().split(".");
      dic["deliver_goods_time"] = strarr[0].toString();
    } else {
      dic["deliver_goods_time"] = timeStr;
    }

    if (otherPriceText.text.length > 0) {
      dic["tips"] = otherPriceText.text;
    }
    dic["goods_remark"] = beiZhuText.text;

    DioUtils.postHttp(
      context,
      "goodsuser/add_order",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        if (t["code"].toString() == "1") {
          showToast("下单成功");
          if (mounted) {
            setState(() {
              beiZhuText.text = "";
              otherPriceText.text = "";
              allPriceStr = "0.00";
            });
          }
          if (payType != "3") {
            toPay(t["data"]["out_trade_no"].toString(), payType);
          }
        } else {
          showToast(t["msg"]);
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  void toPay(String orderID, String payType) {
    DioUtils.postHttp(
      context,
      "payment/order_pay",
      parameters: {
        "token": getData("token"),
        "out_trade_no": orderID,
        "pay_type": payType,
      },
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (payType == "1") {
            tobias.aliPay(t["data"].toString());
          } else if (payType == "2") {
            fluwx.payWithWeChat(
                appId: t["data"]["appid"],
                partnerId: t["data"]["partnerid"],
                prepayId: t["data"]["prepayid"],
                packageValue: t["data"]["package"],
                nonceStr: t["data"]["noncestr"],
                timeStamp: int.parse(t["data"]["timestamp"].toString()),
                sign: t["data"]["sign"]);
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }
}
